<template>
  <div class="room">
    <jm-head></jm-head>
    <section class="center">
      <section class="nav" @click="freshen">
        <section class="nav-item"
                 @click="selected = 1">
          <span :class="{'is-selected': selected === 1}">我的</span>
        </section>
        <section class="nav-item"
                 @click="selected = 2">
          <span :class="{'is-selected': selected === 2}">全部</span>
        </section>
      </section>


      <ul class="post_list_ul" v-infinite-scroll="loadMore"
          infinite-scroll-disabled="loading"
          infinite-scroll-distance="10">
        <li class="post_list_li" v-for="item in roomList" :key="item.id" @click="showRoomDetail(item)">
          <section class="li_header">
            <section class="cover_box">
              <img :src="$store.state.baseImgUrl+item.cover" alt="" class="cover_img">
            </section>
          </section>

          <section class="li_center">
            <section class="li_center_item"><span>空间名：</span>{{item.name}}</section>
            <section class="li_center_item">
            <span class="li_center_item_id">
              <span>空间ID：</span>{{item.id}}
            </span>
              <span class="li_center_item_type" v-show="item.type === -1">
              <i class="icon_style iconfont icon-yonghu"></i>
              <span>个人空间</span>
            </span>
              <span class="li_center_item_type" v-show="item.type === 0">
              <i class="icon_style iconfont icon-unlock_fill"></i>
              <span>公共空间</span>
            </span>
              <span class="li_center_item_type" v-show="item.type === 1">
              <i class="icon_style iconfont icon-lock_fill"></i>
              <span>私人空间</span>
            </span>

            </section>
            <section class="li_center_item">{{item.signature}}</section>
          </section>

        </li>
      </ul>
      <p class="load_content" v-show="!startShowLoading && showLoading">
        <spinner class="load_icon" type="snake"></spinner>
      </p>

    </section>

    <modal
      class="modal"
      :show="showApplicationModal"
      :duration="301"
      @hide="showApplicationModal = false">
      <p class="modal-header">
        <i class="icon_style iconfont icon-tishi">提示</i>
      </p>
      <div class="modal-center">
        <p>该空间为私人空间，需要先向空间管理者申请，才能加入。</p>
        <p>您确定申请加入该空间吗？</p>
        <textarea placeholder="请在这里填写您的验证信息" class="modal-message"></textarea>
      </div>
      <div class="modal-footer">
        <button class="modal-btn modal-ok" @click="application">确定</button>
        <button class="modal-btn modal-cancel" @click="cancel">不了</button>
      </div>
    </modal>

    <modal
      class="modal"
      :show="showRefuseModal"
      :duration="301"
      @hide="showRefuseModal = false">
      <p class="modal-header">
        <i class="icon_style iconfont icon-tishi">提示</i>
      </p>
      <div class="modal-center">
        <p>该空间为个人空间，不允许浏览。</p>
      </div>
      <div class="modal-footer">
        <button class="modal-btn modal-ok" @click="ok">确定</button>
      </div>
    </modal>

    <jm-footer></jm-footer>

    <transition name="loading">
      <spinner class="load_icon" type="snake" v-show="startShowLoading"></spinner>
    </transition>
    <transition name="router-slid" mode="out-in">
      <router-view></router-view>
    </transition>


  </div>
</template>

<script>
  import {mapState, mapMutations} from 'vuex'
  import JmHead from '../../components/header/Head';
  import JmFooter from '../../components/footer/Footer';
  import { Spinner,Toast } from 'mint-ui';
  import Modal from "../../components/common/modal.vue";


  export default {
    data () {
      return {
        selected:1,
        oldSelected:1,
        value:"空间",
        showLoading: true,
        startShowLoading: true,
        loading: false,
        myOffset: 0,
        myRoomList: [],
        allOffset: 0,
        allRoomList: [],
        roomList: [],
        showApplicationModal: false,
        showRefuseModal: false,
        application_message: "",
        room: [],
      }
    },
    mounted(){
      // 如果从详情返回并且之前存有对应的查询条件和参数
      // 则直接渲染之前的数据

      if (window.window.sessionStorage.myRoomList || window.window.sessionStorage.allRoomList) {
        this.myRoomList = JSON.parse(window.window.sessionStorage.myRoomList);
        this.allRoomList = JSON.parse(window.window.sessionStorage.allRoomList);
        this.$nextTick(() => $(window).scrollTop(window.window.sessionStorage.scrollTop));
        if (parseInt(window.window.sessionStorage.selected) === 1){
          this.roomList = this.myRoomList;
          this.myOffset = this.myRoomList.length;
          this.allOffset = this.allRoomList.length;
          this.selected = 1
        }else if(parseInt(window.window.sessionStorage.selected) === 2){
          this.roomList = this.allRoomList;
          this.myOffset = this.myRoomList.length;
          this.allOffset = this.allRoomList.length;
          this.selected = 2
        }else{
          this.myRoomList = [];
          this.allRoomList = [];
        }
      } else {
      }
    },
    beforeRouteLeave(to, from, next) {
      // 如果跳转到详情页面，则记录关键数据
      // 方便从详情页面返回到该页面的时候继续加载之前位置的数据
      if (to.path === '/room') {
        // 当前滚动条位置
        window.window.sessionStorage.scrollTop = $(window).scrollTop();
        // 当前页面数据
        window.window.sessionStorage.allRoomList = JSON.stringify(this.allRoomList);
        window.window.sessionStorage.myRoomList = JSON.stringify(this.myRoomList);
        window.window.sessionStorage.selected = this.selected;
      }
      $(window).off('scroll');
      next();
    },
    beforeRouteEnter(to, from, next) {
      if (from.path !== '/room') {
        // 页面切换移除之前记录的数据集
//        if (window.window.sessionStorage.scrollTop) {
        window.window.sessionStorage.removeItem('roomList');
        window.window.sessionStorage.removeItem('selected');
//        }
      }
      next();
    },
    methods: {
      ...mapMutations([
        'SAVE_ROOM'
      ]),

      freshen(){
        if (this.oldSelected !== this.selected){
          this.loadMore();
          this.oldSelected = this.selected;
        }
      },

      async loadMore(){
        this.loading = true;
        if (this.selected === 1){
          this.roomList = this.myRoomList;
        }else if(this.selected === 2){
          this.roomList = this.allRoomList;
        }

        //获取信息
        let res = null;

        if (this.selected === 1){
          let url = '/v1/room?userId=' + this.$store.state.userInfo.userId
            + '&start=' + this.myOffset
            + '&length=' + this.$store.state.length

          await this.axios.get(url)
            .then(response => {
              res = response.data;
            })
        }else if (this.selected === 2){
          let url = '/v1/room?&start=' + this.allOffset
            + '&length=' + this.$store.state.length

          await this.axios.get(url)
            .then(response => {
              res = response.data;
            })
        }

//        console.log(this.result);
        if (res.success){
          this.startShowLoading = false;
        }else{
          let instance = Toast({message: '网络连接失败', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
        }
        if (this.selected === 1){
          this.myOffset += res.result.length;
          this.myRoomList = [...this.myRoomList, ...res.result];
          this.roomList = this.myRoomList;
        } else if (this.selected === 2){
          this.allOffset += res.result.length;
          this.allRoomList = [...this.allRoomList, ...res.result];
          this.roomList = this.allRoomList;
        }
        if (res.result.length > 0){
          this.loading = false;
        }

        if (res.result.length < this.$store.state.length) {
          this.showLoading = false;
          return
        }
      },

      async showRoomDetail(item){
          if(item.type !== 0){
            let res;
            let url = '/v1/room_follower?userId=' + this.$store.state.userInfo.userId
              + '&roomId=' + item.id
            await this.axios.get(url)
              .then(response => {
                res = response.data;
              })
            if(!res.success){
              if (item.type === -1){
                this.showRefuseModal = true;
              }else{
                this.room = item;
                this.showApplicationModal = true;
              }
              return
            }
          }


        this.SAVE_ROOM(item);
        this.preventRepeat = false;
        this.$router.push('/room');
      },

      async application(){
        let res;
        let url = '/v1/application_info'
        let param = {
          applicatorId: this.$store.state.userInfo.userId,
          applicatorNick: this.$store.state.userInfo.nick,
          content: this.application_message,
          roomId: this.room.id,
          roomName: this.room.name,
          roomCreator: this.room.creatorId,
          status: 0,
          type: 0,
        }
        await this.axios.post(url, param)
          .then(response => {
            res = response.data;
          })
        if (res.success){
          let instance = Toast({message: '申请成功', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
        }else {
          let instance = Toast({message: '网络连接失败', className: 'toast'});
          setTimeout(() => {
            instance.close();
          }, 2000);
        }
        this.application_message = "";
        this.showApplicationModal = false;
      },

      cancel(){
        this.showApplicationModal = false;
      },
      ok(){
          this.showRefuseModal = false;
      }
    },
    components:{
      Modal,
      Spinner,
      JmHead,
      JmFooter
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style lang="scss">
  .mint-toast-text{
    font-size: 0.6rem;
  }
  .toast{
    min-width: 20%;
    width: 20%;
    span{
      color: #FFFFFF;
    }
  }
  .mint-spinner-snake{
    margin: 0 auto;
  }
</style>
<style lang="scss" scoped>
  @import '../../style/mixin';

  .modal{
    .modal-header{
      text-align: center;
      margin: 0.2rem auto;
      .icon_style{
        color: #33CCFF;
      }
      border-bottom: solid 1px #666;
    }
    .modal-center{
      text-align:center;
      .modal-message{
        display: block;
        border-top: solid 1px #666;
        border-bottom: solid 1px #666;
        width: 100%;
        resize: none;
        margin: 0 auto;
        margin-top: 0.6rem;
        font-size: 0.6rem;
        text-indent: 0.5rem;
      }
    }
    .modal-footer{
      display: block;
      width: 100%;
      text-align: center;
      flex-direction: column;
      align-items: center;

      .modal-btn{
        display: block;
        background-color: transparent;
        width: 80%;
        height: 1rem;
        @include borderRadius(0.5rem);
        font-size: 0.6rem;
        margin: 0.4rem auto;
      }
      .modal-ok{
        border:solid 1px #33CCFF;
        color: #33CCFF;
      }
      .modal-cancel{
        border:solid 1px #666;
      }
    }
  }


  .load_icon{
    display: inline-block;
    height: 100%;
    width: 100%;
    position: relative;
    margin: 0 auto;
  }

  .load_content{
    height: 45px;
    width: 100%;
  }

  .center{
    padding-top: 1.5rem;
    padding-bottom: 2rem;
    overflow: hidden;
  }

  .nav{
    background-color: #eaeaea;
    position: fixed;
    z-index: 100;
    left: 0;
    right: 0;
    top: 1.5rem;
    @include wh(100%, 0.88rem);
    display: flex;
    box-shadow: 0 -0.026667rem 0.053333rem rgba(0,0,0,.1);

    .nav-item{
      flex: 1;
      display: flex;
      text-align: center;
      flex-direction: column;
      align-items: center;
      @include sc(.5rem, #666);

      span{
        margin: auto auto;
      }

      .is-selected{
        color: #33CCFF;
      }
    }
  }


  .post_list_ul{
    padding-top: 0.88rem;

    .post_list_li{
      border: solid 1px #d7dde4;
      @include borderRadius(0.1rem);
      border-bottom: solid 10px #eaeaea;
      box-shadow: 0 -0.026667rem 0.053333rem rgba(0,0,0,.1);


      /*单个文章节点头部 开始*/
      .li_header{
        border: solid 1px #d7dde4;
        padding-top: 10px;
        padding-bottom: 10px;
        .cover_box{
          display: flex;
          flex: 1;
          margin: 0 10px;
          .cover_img{
            flex: 1;
            display: flex;
            @include wh(0rem, 5rem);
          }

        }
      }

      .li_center{

        .li_center_item{
          font-size: 0.6rem;
          margin: 2px 10px;

          .li_center_item_id{
            margin-right: 66px;
          }
          .li_center_item_type{
              .icon_style{
                font-size: 0.6rem;
              }
          }
        }

      }


    }
  }

  span,input{
    font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;
  }






</style>
